import { useState } from 'react'
import { HomePath } from '@/common/constants'
import { useModel } from 'umi'
import { isPlainObject } from 'lodash'

export default () => {
  const { StorgeSet, StorgeGet } = useModel('storge')
  const opened: any = StorgeGet({ path: 'tags.opened' })
  const fixed = { title: '公告板', path: HomePath }
  const [tagList, setTagList] = useState(isPlainObject(opened) ? [fixed] : [...opened])

  const save = (value: any) => {
    StorgeSet({ path: 'tags.opened', value })
  }

  const reducers = {
    addTag(tag: any) {
      const hasTag = tagList.some((item: any) => item.path === tag.path)
      const newTag = hasTag ? tagList : [...tagList, tag]

      setTagList(newTag)
      save(newTag)
    },
    deleteTag(tag: any) {
      const newTag = [...tagList.filter((item: any) => item !== tag)]

      setTagList(newTag)
      save(newTag)
    },
    emptyTag() {
      const newTag = [...tagList.filter((item: any) => item.path === HomePath)]
      setTagList(newTag)
      save(newTag)
    },
    closeLeftTags(path: string, index: number) {
      const curIndex = index ?? tagList.findIndex((item: any) => item.path === path)
      const newTag = tagList.filter((item: any, i: number) => i >= curIndex)

      setTagList(newTag)
      save(newTag)
    },
    closeRightTags(path: string, index: number) {
      const curIndex = index ?? tagList.findIndex((item: any) => item.path === path)
      const newTag = tagList.filter((item: any, i: number) => i <= curIndex)

      setTagList(newTag)
      save(newTag)
    },
    closeOtherTag(action: any) {
      const newTag = [...tagList.filter((item: any) => item.path === HomePath || item === action.tag)]

      setTagList(newTag)
      save(newTag)
    },
  }

  return {
    tagList,
    setTagList,
    ...reducers,
  }
}
